package session

import (
	"github.com/satori/go.uuid"
	"sync"
	"time"
	"video_server/api/dbops"
	"video_server/api/defs"
)



var sessionMap *sync.Map

func init(){
	sessionMap = &sync.Map{}
}

func deleteExpiredSession(sid string){
	sessionMap.Delete(sid)
	dbops.DeleteSession(sid)
}

func nowInMilli() int64{
	return time.Now().UnixNano()/1000000
}

func LoadSessionsFromDB()  {
	r,err := dbops.RetrieveAllSession()
	if err != nil {
		return
	}
	r.Range(func(key, value interface{}) bool {
		ss :=value.(*defs.SimpleSession)
		sessionMap.Store(key,ss)
		return true
	})
}

func GenerateNewSessionId(un string) string  {
	uuid, _ := uuid.NewV4()
	id := uuid.String()
	ct := nowInMilli()
	ttl :=ct + 30*60*1000
	ss :=&defs.SimpleSession{Username:un,TTL:ttl}
	sessionMap.Store(id,ss)
	dbops.InsertSession(id,ttl,un)
	return id
}

func IsSessionExpired(sid string) (string,bool)  {

	ss,ok := sessionMap.Load(sid)
	if ok {
		ct := nowInMilli()
		if ss.(*defs.SimpleSession).TTL < ct{
			deleteExpiredSession(sid)
			return "",true
		}
		return ss.(*defs.SimpleSession).Username,false
	}
	return "",true
}